/**
 * @FileName: ActivityOrderService.java
 * @Author
 * @Description:
 * @Date 2017年4月5日 上午9:00:00
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.fastjson.JSONArray;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.util.InterfaceUtil;

public class ActivityOrderService{
    public static final ActivityOrderService service                                 = new ActivityOrderService();
    /**
     * @Title: getActivityOrderByOrderId
     * @Description:TODO
     * @param str
     * @return Record
     */

    public Record getActivityOrderByOrderId(String orderId){
        String sql = "select cc.pos_id,cc.pub,coa.* from cmcc_order_activity coa left join member_org mo on mo.id=coa.user_id left join organization o on o.id=mo.org_id left join cmcc_city city on city.group_id=(select org.NumCode from organization org where org.id=o.CityCode) left join city_counter cc on cc.cmcc_city_id=city.id where coa.order_id=?";

        return Db.findFirst(sql, orderId);
    }

    public String getSqlSelect(){
        String sql = " select o.*," + InterfaceUtil.getCitySql("o.org_id") + " as city, "
                + InterfaceUtil.getAreaSql("o.org_id") + " as area, "
                + " org.NumCode, org.DisplayName,  (select class_name from organization_class where enabled = '1' and id = org.webSiteId) as sitetype,  "
                + "DATE_FORMAT(o.pay_time,'%Y-%m-%d %T') as pay_datetime ,DATE_FORMAT(o.create_time,'%Y-%m-%d %T') as created_datetime,o.user_mobile as staff_phone,o.user_name as staff_name,m.emp_code,(case o.pay_plat when 14 then '支付宝' when 15 then '建行' when 16 then '银联' else '出错' end)as pay_method,(case o.pay_status when 0 then '未支付' when 1 then '已支付' when 2 then '支付失败' when 5 then '已退款' when 6 then '退款失败' else '出错' end)as pay_state,(case o.order_state when 1 then '办理成功' when 0 then '办理失败' end)as order_status,sp.order_id as cmcc_id";
        return sql;
    }

    public String getSqlFilter(ConcurrentHashMap<String, Object> searchInfo){
        String sqlExceptSelect = " from cmcc_order_activity o left join member_org m on o.user_id=m.id left join organization org on o.org_id=org.id left join sales_promotion sp on o.order_id=sp.thirdpart_id where 1=1 ";

        for(Entry<String, Object> item : searchInfo.entrySet()){
            sqlExceptSelect += appendQueryFilter(item);
        }
        sqlExceptSelect += " ORDER BY o.create_time DESC";

        return sqlExceptSelect;
    }

    /**
     * @Title: buildQuery
     * @Description:追加查询条件
     */
    private String appendQueryFilter(Entry<String, Object> item){
        StringBuilder sb = new StringBuilder();
        Object valueObj = item.getValue();
        String value = "";
        String key = item.getKey();
        if(null != valueObj){
            value = String.valueOf(valueObj);
        }
        switch(key){
            // case "org_id":
            // sb.append(getSubOrgIdFilter(value));
            // break;
            case "order_id":
                sb.append(getAndLikeFilter("o.order_id", value));
                break;
            case "phone_number":
                sb.append(getAndLikeFilter("o.client_mobile", value));
                break;
            case "cmcc_id":
                sb.append(getAndLikeFilter("sp.order_id", value));
                // System.out.println("subsql:" +
                // getAndLikeFilter("sp.thirdpart_id", value));
                break;
            case "staff_phone":
                sb.append(getAndLikeFilter("m.mobile", value));
                break;
            case "tariff_code":
                sb.append(getAndLikeFilter("o.tariff_code", value));
                break;
            case "package_name":
                sb.append(getAndLikeFilter("o.package_name", value));
                break;
//            case "pay_plat":
//                if(!value.equals("-1")){
//                    sb.append(getPayPlatFilter(value));
//                }
//                break;
//            case "pay_status":
//                JSONArray valueJA = JSONArray.parseArray(value);
//                sb.append(getPayStatusFilter("o.pay_status", valueJA));
//                break;
            case "order_status":
                if(!value.equals("-1")){
                    sb.append(getOrderStatusFilter(value));
                }
                break;

            case "start_date":
                sb.append(getStartTimeFilter(value));
                break;
            case "end_date":
                sb.append(getEndTimeFilter(value));
                break;
            case "org_id":
                sb.append(getOrgLimit(value));
                break;
            default:
                break;
        }
        return sb.toString();
    }

    /**
     * @Title: getPayStatusFilter
     * @Description:TODO
     * @param string
     * @param valueJA
     * @return Object
     */
    private Object getPayStatusFilter(String keyName, JSONArray valueJA){
        String sql = "";
        boolean isAll = false;
        for(int i = 0, len = valueJA.size(); i < len; i++){
            String va = (String)valueJA.get(i);
            if(i == 0){
                if(!"-1".equals(va)){
                    sql += " AND (" + keyName + " = " + va;
                } else{
                    isAll = true;
                }
            } else{
                if(!"-1".equals(va)){
                    if(isAll){
                        sql += " AND (" + keyName + " = " + va;
                        isAll = false;
                    } else{
                        sql += " OR " + keyName + " = " + va;
                    }
                }
            }
            if((i == len - 1) && !isAll){
                sql += ")";
            }

        }

        return StrKit.notBlank(sql) ? String.format(sql) : "";
    }

    /**
     * @Title: getOrgLimit
     * @Description:TODO
     * @param string
     * @return Object
     */
    private Object getOrgLimit(String orgId){
        String sql = " and o.org_id in("
                + InterfaceUtil.getChlidOrgIdSql(Integer.parseInt(orgId), Constant.MAX_ORG_LEVEL, true) + ") ";
        return String.format(sql);
    }

    private String getPayPlatFilter(String value){
        if(value.equals("1")){
            return String.format(" AND o.pay_plat = 14 ");
        } else{
            return String.format(" AND ((o.pay_plat = 15) OR (o.pay_plat = 16)) ");
        }

    }

    private String getOrderStatusFilter(String value){
//        if(value.equals("1")){
//            return String.format(" AND o.order_state = 5 ");
//        } else{
//            return String
//                    .format(" AND ((o.order_state = 0 ) OR (o.order_state = 1) OR (o.order_state = 6) OR (o.order_state = 7) OR (o.order_state = 8)) ");
//        }
    	return String.format("AND o.order_state = " + value);

    }

    /**
     * @Title: getEndTimeFilter
     * @Description:获取开始时间查询条件
     */
    private String getEndTimeFilter(String value){
        return String.format(" AND o.create_time <= '%s 23:59:59' ", value);
    }

    /**
     * @Title: getStartTimeFilter
     * @Description:获取结束时间查询条件
     */
    private String getStartTimeFilter(String value){
        return String.format(" AND o.create_time >= '%s 00:00:00' ", value);
    }

    /**
     * @Title: getAndLikeFilter
     * @Description:获取KeyName和value模糊查询条件
     */
    private String getAndLikeFilter(String keyName, String value){
        return String.format(" AND %s LIKE '%%%s%%' ", keyName, value);
    }
}
